package com.ats.orderknot.client;

import java.util.Date;
import java.util.List;

import com.ats.orderknot.shared.FieldVerifier;
import com.bradrydzewski.gwt.calendar.client.Appointment;
import com.bradrydzewski.gwt.calendar.client.AppointmentStyle;
import com.bradrydzewski.gwt.calendar.client.Calendar;
import com.bradrydzewski.gwt.calendar.client.CalendarSettings;
import com.bradrydzewski.gwt.calendar.client.event.CreateEvent;
import com.bradrydzewski.gwt.calendar.client.event.CreateHandler;
import com.bradrydzewski.gwt.calendar.client.event.DateRequestEvent;
import com.bradrydzewski.gwt.calendar.client.event.DateRequestHandler;
import com.bradrydzewski.gwt.calendar.client.event.MouseOverEvent;
import com.bradrydzewski.gwt.calendar.client.event.MouseOverHandler;
import com.bradrydzewski.gwt.calendar.client.event.TimeBlockClickEvent;
import com.bradrydzewski.gwt.calendar.client.event.TimeBlockClickHandler;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.i18n.shared.DateTimeFormat;
import com.google.gwt.i18n.shared.DateTimeFormat.PredefinedFormat;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DecoratedPopupPanel;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class OrderKnot implements EntryPoint {
  /**
   * The message displayed to the user when the server cannot be reached or
   * returns an error.
   */
  private static final String SERVER_ERROR = "An error occurred while "
      + "attempting to contact the server. Please check your network "
      + "connection and try again.";

  /**
   * Create a remote service proxy to talk to the server-side Greeting service.
   */
  public final static GreetingServiceAsync greetingService = GreetingServiceAsync.Util.getInstance();


  private final Messages messages = GWT.create(Messages.class);

  public final static DateTimeFormat df = DateTimeFormat.getFormat(PredefinedFormat.DATE_TIME_LONG);

  /**
   * This is the entry point method.
   */
  public void onModuleLoad() {
    final Button sendButton = new Button( messages.sendButton() );
    final TextBox nameField = new TextBox();
    nameField.setText( messages.nameField() );
    final Label errorLabel = new Label();

    // We can add style names to widgets
    sendButton.addStyleName("sendButton");

    // Add the nameField and sendButton to the RootPanel
    // Use RootPanel.get() to get the entire body element
    RootPanel.get("nameFieldContainer").add(nameField);
    RootPanel.get("sendButtonContainer").add(sendButton);
    RootPanel.get("errorLabelContainer").add(errorLabel);
    
    CalendarSettings settings = new CalendarSettings();
    settings.setPixelsPerInterval(15);


    final Calendar calendar = new Calendar();
    calendar.setSettings(settings);
    calendar.setDate(new Date()); //calendar date, not required
    calendar.setDays(7); //number of days displayed at a time, not required
    //calendar.setWidth("500px");
    //calendar.setHeight("400px");
    RootPanel.get("calendar").add(calendar);



    
    calendar.addDateRequestHandler(new DateRequestHandler<Date>() {
		
		public void onDateRequested(DateRequestEvent<Date> event) {
			System.out.println("DateRequestHandler"+event.getTarget());
			System.out.println("DateRequestHandler"+event.getSource());
		}
	});

//#import <Foundation/Foundation.h>
//
//@interface TTPrzetarg : NSObject 
//
//@property (nonatomic) NSTimeInterval ID; // event cretion time (works as event ID)
//@property (nonatomic, retain) NSDate *date; // event date
//@property (nonatomic, retain) NSString *title; // event title
//@property (nonatomic, retain) NSString *subtitle; // event subtitle (sometimes comes handy...)
//@property (nonatomic, retain) NSString *description; // event description
//@property (nonatomic) CLLocationCoordinate2D coordinate; // event coords
//
//@end
 
    final AppointmentEditor appEditor = new AppointmentEditor(calendar);
    
    calendar.addTimeBlockClickHandler(new TimeBlockClickHandler<Date>(){
        public void onTimeBlockClick(TimeBlockClickEvent<Date> event) {
                Date startDate = event.getTarget();
                appEditor.getAppStartDate().setText(OrderKnot.df.format(startDate));
                appEditor.getAppEndDate().setText(OrderKnot.df.format(new Date(startDate.getTime() + 1000 * 60 * 60)));
                appEditor.center();
                appEditor.show();
        }
    });

    
    
    final DecoratedPopupPanel appointmentPopup = new DecoratedPopupPanel(true);
    appointmentPopup.setAutoHideEnabled(true);

    calendar.addCreateHandler(new CreateHandler<Appointment>() {
		public void onCreate(CreateEvent<Appointment> event) {
			greetingService.saveAppointment(event.getTarget(), new AsyncCallback<Boolean>() {
				public void onSuccess(Boolean arg0) {
					if (arg0){
						//ok
					} else {
						//jak wykonac!!
						//event.setCancelled(true);
					}
				}
				
				public void onFailure(Throwable arg0) {
				}
			});
		}
	});
    
    calendar.addMouseOverHandler(new MouseOverHandler<Appointment>(){
    	public void onMouseOver(MouseOverEvent<Appointment> event) {
    	           Element element = (Element)event.getElement();
    	           appointmentPopup.setWidget(new HTML("To jest napis autopoup:<br>"+event.getTarget().getTitle()));
    	           int left = element.getAbsoluteLeft() + 10;
    	           int top = element.getAbsoluteTop() + 10;
    	           appointmentPopup.setPopupPosition(left, top);
    	           appointmentPopup.show();
    	}
    });
    
    greetingService.getAppointments(new AsyncCallback<List<Appointment>>() {		
		public void onSuccess(List<Appointment> ret) {
			calendar.suspendLayout();
			for (Appointment appointment : ret) {
		        calendar.addAppointment(appointment);
			}
			calendar.resumeLayout();
		}
		public void onFailure(Throwable arg0) {
		}
	});
    
    
    // Focus the cursor on the name field when the app loads
    nameField.setFocus(true);
    nameField.selectAll();

    // Create the popup dialog box
    final DialogBox dialogBox = new DialogBox();
    dialogBox.setText("Remote Procedure Call");
    dialogBox.setAnimationEnabled(true);
    final Button closeButton = new Button("Close");
    // We can set the id of a widget by accessing its Element
    closeButton.getElement().setId("closeButton");
    final Label textToServerLabel = new Label();
    final HTML serverResponseLabel = new HTML();
    VerticalPanel dialogVPanel = new VerticalPanel();
    dialogVPanel.addStyleName("dialogVPanel");
    dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
    dialogVPanel.add(textToServerLabel);
    dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
    dialogVPanel.add(serverResponseLabel);
    dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
    dialogVPanel.add(closeButton);
    dialogBox.setWidget(dialogVPanel);

    // Add a handler to close the DialogBox
    closeButton.addClickHandler(new ClickHandler() {
      public void onClick(ClickEvent event) {
        dialogBox.hide();
        sendButton.setEnabled(true);
        sendButton.setFocus(true);
      }
    });

    // Create a handler for the sendButton and nameField
    class MyHandler implements ClickHandler, KeyUpHandler {
      /**
       * Fired when the user clicks on the sendButton.
       */
      public void onClick(ClickEvent event) {
        sendNameToServer();
      }

      /**
       * Fired when the user types in the nameField.
       */
      public void onKeyUp(KeyUpEvent event) {
        if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
          sendNameToServer();
        }
      }

      /**
       * Send the name from the nameField to the server and wait for a response.
       */
      private void sendNameToServer() {
        // First, we validate the input.
        errorLabel.setText("");
        String textToServer = nameField.getText();
        if (!FieldVerifier.isValidName(textToServer)) {
          errorLabel.setText("Please enter at least four characters");
          return;
        }

        // Then, we send the input to the server.
        sendButton.setEnabled(false);
        textToServerLabel.setText(textToServer);
        serverResponseLabel.setText("");
        greetingService.greetServer(textToServer, new AsyncCallback<String>() {
          public void onFailure(Throwable caught) {
            // Show the RPC error message to the user
            dialogBox.setText("Remote Procedure Call - Failure");
            serverResponseLabel.addStyleName("serverResponseLabelError");
            serverResponseLabel.setHTML(SERVER_ERROR);
            dialogBox.center();
            closeButton.setFocus(true);
          }

          public void onSuccess(String result) {
            dialogBox.setText("Remote Procedure Call");
            serverResponseLabel.removeStyleName("serverResponseLabelError");
            serverResponseLabel.setHTML(result);
            dialogBox.center();
            closeButton.setFocus(true);
          }
        });
      }
    }

    // Add a handler to send the name to the server
    MyHandler handler = new MyHandler();
    sendButton.addClickHandler(handler);
    nameField.addKeyUpHandler(handler);
  }
}
